package com.da.lon.wang.xlg.util;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Process;
import android.util.Base64;
import android.util.DisplayMetrics;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

public final class OtherUtil {

    /**
     * 获取明天开始时间
     *
     * @return
     */
    public static long getTomorrowStart() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DATE, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);

        return calendar.getTimeInMillis();
    }

    /**
     * 解析 URL
     *
     * @param urlString
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String parseURL(String urlString) throws UnsupportedEncodingException {
        if (urlString == null || urlString.trim().equals(""))
            return urlString;

        try {
            urlString = URLEncoder.encode(urlString, "UTF-8");
        } catch (Exception e) {
        }

        try {
            urlString = urlString.replaceAll("\\+", "%20");
        } catch (Exception e) {
        }

        try {
            urlString = urlString.replaceAll("%3A", ":");
        } catch (Exception e) {
        }

        try {
            urlString = urlString.replaceAll("%2F", "/");
        } catch (Exception e) {
        }

        try {
            urlString = urlString.replaceAll("%3F", "?");
        } catch (Exception e) {
        }

        try {
            urlString = urlString.replaceAll("%3D", "=");
        } catch (Exception e) {
        }

        try {
            urlString = urlString.replaceAll("%26", "&");
        } catch (Exception e) {
        }

        try {
            urlString = urlString.replaceAll("%25", "%");
        } catch (Exception e) {
        }

        return urlString;
    }

    /**
     * 打开安装程序
     *
     * @param context
     * @param apkFile
     */
    public static void openInstall(Context context, File apkFile) {

        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

    /**
     * 判断 APP 是否安装
     *
     * @param apkPkg
     * @return
     */
    public static boolean isInstall(Context context, String pkg) {
        // 判断程序是否正确安装
        try {
            return (context.getPackageManager().getPackageInfo(pkg, PackageManager.GET_ACTIVITIES) != null);
        } catch (NameNotFoundException e) {
        }

        return false;
    }

    /**
     * 启动 APP
     *
     * @param context
     * @param pkg
     * @return
     */
    public static boolean startApp(Context context, String pkg) {
        PackageInfo packageInfo;
        ResolveInfo resolveInfo;
        ComponentName componentName;
        Intent newIntent;
        PackageManager manager = context.getPackageManager();

        // // 判断程序是否启动
        // for (RunningTaskInfo taskInfo : activityManager.getRunningTasks(10))
        // {
        // if (taskInfo.baseActivity.getPackageName().equals(pkg))
        // return true;
        // }

        // 判断程序是否正确安装
        if (false == isInstall(context, pkg)) {
            return false;
        }

        try {
            packageInfo = manager.getPackageInfo(pkg, 0);
            newIntent = new Intent(Intent.ACTION_MAIN, null);
            newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
            newIntent.setPackage(packageInfo.packageName);

            // 查找入口
            resolveInfo = manager.queryIntentActivities(newIntent, 0).iterator().next();
            if (resolveInfo != null) {

                componentName = new ComponentName(resolveInfo.activityInfo.packageName, resolveInfo.activityInfo.name);
                newIntent = new Intent(Intent.ACTION_MAIN);
                newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
                newIntent.setComponent(componentName);
                try {
                    context.startActivity(newIntent);
                } catch (Exception e) {
                }
            }
        } catch (Exception e) {
        }

        return true;
    }

    /**
     * 获取 apk 包的 package
     *
     * @param context
     * @param archiveFilePath
     */
    public static String getApkPkg(Context context, String archiveFilePath) {
        try {
            PackageManager pm = context.getPackageManager();
            if (pm == null)
                return null;

            PackageInfo info = pm.getPackageArchiveInfo(archiveFilePath, PackageManager.GET_ACTIVITIES);
            if (info == null) {
                return null;
            }

            return info.packageName;
        } catch (Exception e) {
        }

        return null;
    }

    /**
     * 发送事件广播
     *
     * @param context
     * @param receiver
     * @param businessType
     * @param num
     */
    public static void sendBroadcast(Context context, String pkg) {
        Intent intent = new Intent("update_listview");
        intent.putExtra("package", pkg);
        context.sendBroadcast(intent);
    }

    /**
     * md5 加密
     *
     * @param s
     * @return
     */
    public static String md5(String s) {
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        try {
            byte[] btInput = s.getBytes();
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return s;
        }
    }

    /**
     * 分辨率
     *
     * @param context
     * @return
     */
    public static String getPIX(Context context) {
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        return metrics.widthPixels + "X" + metrics.heightPixels;
    }

    /**
     * 系统
     *
     * @param context
     * @return
     */
    public static String getOS() {
        return Build.FINGERPRINT.replace("\\^", " ");
    }

    /**
     * 品牌
     *
     * @return
     */
    public static String getBrand() {
        return Build.MANUFACTURER.replace("\\^", " ") + ";" + Build.MODEL.replace("\\^", " ");
    }

    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    public static int getVersion(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            return info.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return 0;
    }

    /**
     * 错误提示
     *
     * @param activity
     */
    public static void onFaile(Activity activity) {
        if (activity == null || activity.isFinishing()) {
            Process.killProcess(Process.myPid());
            return;
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setCancelable(true);
        builder.setTitle("错误").setMessage("请使用正版软件......");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        AlertDialog dialog = builder.create();
        dialog.setOnDismissListener(new OnDismissListener() {

            @Override
            public void onDismiss(DialogInterface dialog) {
                // TODO Auto-generated method stub
                Process.killProcess(Process.myPid());
            }
        });
        if (false == dialog.isShowing()) {
            dialog.show();
        }
    }

    public static void onNetworkFaile(Activity activity) {
        if (activity == null || activity.isFinishing()) {
            return;
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setCancelable(true);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setTitle("网络不可用");
        builder.setMessage("请检查网络连接是否正常。");
        Dialog dialog = builder.create();
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);
        if (false == dialog.isShowing()) {
            dialog.show();
        }
    }

    public static String genIdentity() {
        return UUID.randomUUID().toString().replace("-", "");
    }


    private static String parseSignInfo(byte[] signature) {
        // TODO Auto-generated method stub
        try {
            CertificateFactory factory = CertificateFactory.getInstance("X.509");
            X509Certificate cert = (X509Certificate) factory.generateCertificate(new ByteArrayInputStream(signature));
            byte[] buffer = cert.getEncoded();

            return md5(Base64.encodeToString(buffer, Base64.NO_WRAP));
        } catch (Exception e) {
        }
        return "parse error";
    }
}
